package com.kvest.looper_test.Looper;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;


/**
 * Created with IntelliJ IDEA.
 * User: r.belokon
 * Date: 29.04.13
 * Time: 9:26
 * To change this template use File | Settings | File Templates.
 */
public class LoopThread implements Runnable {
    private Handler customHandler;
    private Handler emptyHandler;
    private Handler callbackHandler;
    private Looper looper;

    public void start() {
        new Thread(this).start();
    }

    public void stop() {
        if (looper != null) {
            looper.quit();
        }
    }

    @Override
    public void run() {
        Looper.prepare();

        looper = Looper.myLooper();

        customHandler = new Handler() {
            public void handleMessage(Message msg) {
                Log.d("LOOPER_TEST", "custom handler=" + msg.toString());
                if (msg.what == 1) {
                    Log.d("LOOPER_TEST", "String =" + (String)msg.obj);
                } else {
                    Log.d("LOOPER_TEST", "unknown =" + msg.toString());
                }
            }
        };

        emptyHandler = new Handler();

        callbackHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                Log.d("LOOPER_TEST", "callback handler=" + message.toString());
                if (message.what == 1) {
                    Log.d("LOOPER_TEST", "String =" + (String)message.obj);
                } else {
                    Log.d("LOOPER_TEST", "unknown =" + message.toString());
                }

                return true;
            }
        });

        Looper.loop();

        Log.d("LOOPER_TEST", "thread finished");
    }

    public Handler getCustomHandler() {
        return customHandler;
    }

    public Handler getEmptyHandler() {
        return emptyHandler;
    }

    public Handler getCallbackHandler() {
        return callbackHandler;
    }
}
